package bma.common.langutil.jmshell.command;

import bma.common.langutil.jmshell.Session;
import bma.common.langutil.jmshell.cmdopt.CommandOptionParser;
import bma.common.langutil.jmshell.cmdopt.OptionException;

public abstract class AbstractSimpleCommandProcessor extends CommandProcessor {

	public AbstractSimpleCommandProcessor(String command) {
		super(command);
	}

	@Override
	public boolean process(Session session, String text) {
		if (canHandle(session, text)) {
			CommandOptionParser co = createCommandOption(session);
			if (co != null) {
				if (!co.hasOption("help")) {
					co.addBooleanOption('h', "help", null);
				}
				String cmd = null;
				try {
					cmd = co.parse(text);
				} catch (OptionException e) {
					StringBuilder sb = new StringBuilder();
					sb.append(e.getMessage()).append("\n");
					sb.append(getHelp(session));
					session.writeln(sb.toString());
					return true;
				}

				if (co.getOptionValue("help", Boolean.FALSE)) {
					session.writeln(getHelp(session));
					return true;
				}

				return processCommand(session, cmd, co);
			}
		}
		return false;
	}

	public abstract CommandOptionParser createCommandOption(Session session);

	public abstract boolean processCommand(Session session, String cmd,
			CommandOptionParser options);

	@Override
	public String getHelp(Session session) {
		CommandOptionParser co = createCommandOption(session);
		if (co != null) {
			return co.getHelpString(getCommand(), getArgsTips());
		}
		return "no help";
	}
}
